package com.qian2.pricesharingapplication;


import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.lb2.JSONParser;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class ChooseAccount extends Activity{
	private static final int AUTHORIZATION_CODE = 1993;
	private static final int ACCOUNT_CODE = 1601;
	
	private AuthPreferences authPreferences;
	private AccountManager accountManager;
	private final String SCOPE = "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email";
	
	public static final String MyPREFERENCES = "MyPrefs";
	public static final String Email = "emailKey";
//	static SharedPreferences sharedpreferences;
		
	JSONParser jsonParser = new JSONParser();
	private static final String TAG_SUCCESS = "success";
	private static String url_create_users = "http://wwwfyp.cse.ust.hk:7117/create_user.php";
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		accountManager = AccountManager.get(this);
		authPreferences = new AuthPreferences(this);

		//test
//		sharedpreferences = getSharedPreferences(MyPREFERENCES,
//				Context.MODE_PRIVATE);
		if (authPreferences.getUser() != null
				&& authPreferences.getToken() != null) {
			// doCoolAuthenticatedStuff();
			// System.out.println("User: "+authPreferences.getUser());
			// System.out.println("Token: "+authPreferences.getToken());

		} else {
			chooseAccount();
			// TextView textview=(TextView) this.findViewById(R.id.output);
			// textview.setText(authPreferences.getUser());

			// TextView textview2=(TextView) this.findViewById(R.id.testing);
			// textview2.setText(authPreferences.getToken());
		}
		/*	if(authPreferences.getUser() != null){
				System.out.println("2 stat: user: "+authPreferences.getUser());}
			*/
		if (MainActivity.sharedpreferences.contains(Email)) {
			System.out.println("Email: "
					+ MainActivity.sharedpreferences.getString(Email, ""));

		}
	}
	private void doCoolAuthenticatedStuff() {
		// TODO: insert cool stuff with authPreferences.getToken()

		Log.e("AuthApp", authPreferences.getToken());
		System.out.println("user: " + authPreferences.getUser());
		if (!MainActivity.sharedpreferences.contains(Email)) {
			Editor editor = MainActivity.sharedpreferences.edit();
			editor.putString(Email, authPreferences.getUser());
			editor.commit();
			new CreateUser().execute();
		}
	}

	private void chooseAccount() {
		// use https://github.com/frakbot/Android-AccountChooser for
		// compatibility with older devices
		Intent intent = AccountManager.newChooseAccountIntent(null, null,
				new String[] { "com.google" }, false, null, null, null, null);
		startActivityForResult(intent, ACCOUNT_CODE);
	}

	private void requestToken() {
		Account userAccount = null;
		String user = authPreferences.getUser();
		for (Account account : accountManager.getAccountsByType("com.google")) {
			if (account.name.equals(user)) {
				userAccount = account;

				break;
			}
		}

		accountManager.getAuthToken(userAccount, "oauth2:" + SCOPE, null, this,
				new OnTokenAcquired(), null);
		finish();
	}

	/**
	 * call this method if your token expired, or you want to request a new
	 * token for whatever reason. call requestToken() again afterwards in order
	 * to get a new token.
	 */
	private void invalidateToken() {
		AccountManager accountManager = AccountManager.get(this);
		accountManager.invalidateAuthToken("com.google",
				authPreferences.getToken());

		authPreferences.setToken(null);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {
			if (requestCode == AUTHORIZATION_CODE) {
				requestToken();
			} else if (requestCode == ACCOUNT_CODE) {
				String accountName = data
						.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
				authPreferences.setUser(accountName);

				// invalidate old tokens which might be cached. we want a fresh
				// one, which is guaranteed to work
				invalidateToken();

				requestToken();
			}
		}
	}

	private class OnTokenAcquired implements AccountManagerCallback<Bundle> {

		@Override
		public void run(AccountManagerFuture<Bundle> result) {
			try {
				Bundle bundle = result.getResult();

				Intent launch = (Intent) bundle.get(AccountManager.KEY_INTENT);
				if (launch != null) {
					startActivityForResult(launch, AUTHORIZATION_CODE);
				} else {
					String token = bundle
							.getString(AccountManager.KEY_AUTHTOKEN);

					authPreferences.setToken(token);

					doCoolAuthenticatedStuff();
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
	class CreateUser extends AsyncTask<String, String, JSONObject> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// pDialog = new ProgressDialog(MainActivity.this);
			// pDialog.setMessage("Creating Product..");
			// pDialog.setIndeterminate(false);
			// pDialog.setCancelable(true);
			// pDialog.show();
		}

		/**
		 * Creating user
		 * */
		protected JSONObject doInBackground(String... args) {
			String name = authPreferences.getUser().toString();

			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("name", name));
			for (int i = 0; i < params.size(); i++) {
				Log.d("Create Response for params", params.get(i).toString());

			}

			// getting JSON Object
			// Note that create product url accepts POST method
			JSONObject json = jsonParser.makeHttpRequest(url_create_users,
					"POST", params);

			// check log cat fro response
			System.out.println("user: Response from server" + json.toString());

			// check for success tag
			try {
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// successfully created product
				} else {
					// failed to create product

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return json;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(JSONObject json) {

		}

	}
}
